import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Button, Balloon, Tag, Dropdown, Menu } from '@teamix/ui';
import { Title, Layout, Header, Body, BodyContent, Content, YunxiaoIcon } from '@alife/devops-ui';
import { ENUM, ORGANIZATION_ADMIN_ROLES } from 'utils/constants.js';
import utils from 'utils/index';
import { navigateOpen } from 'utils/router';
import List from '@txdfe/at-list';
import TextAvatar from '@txdfe/at-text-avatar';
import ListLoading from 'atComponents/ListLoading';
import CreateProjectModal from 'components/createProjectModal';
import { access } from 'components/accessContainer/util';
import * as actions from '../actions/index';
// import TbBuildResultTag from './buildsResult';
import BalloonConfirm from 'components/ballonConfirm';
import './index.scss';
import LinkProjectModal from '@alife/yunxiao-link-repo';
import { AppSDK } from 'tb-apps-sdk';
import { hostAPI } from 'tb-apps-sdk/api/app-tab';
import track, { enterPage, Perf } from 'utils/track';
import PathEllipsis from 'components/pathEllipsis';
import intl from '../../../locale';

const webApp = AppSDK.fork(hostAPI);
webApp.init();

const tbProjectId = utils.getUrlSearchParam('projectId');

const defaultNamespaceId = utils.getUrlSearchParam('namespace_id');

const { user_role } = window.FORCE.organization;
// const PROJECT_ROLES = ['REPORTER', 'ORG_MEMBER', 'DEVELOPER', 'MASTER', 'OWNER', 'ORG_ADMIN', 'ORG_OWNER', 'ADMIN'];

const { visibility_levels } = ENUM;

class Root extends Component {
  static propTypes = {
    projects: PropTypes.arrayOf(PropTypes.object),
    // currentPage: PropTypes.number,
    total: PropTypes.number,
  };

  static defaultProps = {
    projects: null,
    currentPage: 1,
    total: 0,
    order_by: 'last_activity_at',
  };

  state = {
    createModalShow: false,
    linkModalShow: false,
  };

  componentDidMount() {
    this.props.getProjects(1);
    this.props.getRepoSettingData();
    window.addEventListener('message', this.handleMessage);
    // 获取tbproject项目信息
    this.props.getTbProjectInfo();

    enterPage('DevOps Codeup Page', {
      sendPerf: false,
    });
  }

  componentWillUnmount() {
    window.removeEventListener('message', this.handleMessage);
  }

  handleMessage = (event) => {
    const { style, type, sidebarStatus } = event.data;
    if (type === 'changeStyle') {
      if (style) {
        for (const key in style) {
          document.body.style[key] = style[key];
        }
      }
      if (sidebarStatus) {
        // normal || mini
        document.body.dataset.sidebar = sidebarStatus;
      }
    }
  };

  reloadData = () => {
    this.props.getProjects(1);
  };

  getCreateProjectAccess = () => {
    const { repoCreatorIdentity } = this.props;
    return (
      access(ORGANIZATION_ADMIN_ROLES, user_role) ||
      repoCreatorIdentity.map((item) => ENUM.access_level[item]).includes(user_role)
    );
  };

  renderAddBtn = (type = 'primary') => {
    const hasCreateProjectAccess = this.getCreateProjectAccess();
    if (!hasCreateProjectAccess) {
      return (
        <Balloon.Tooltip
          trigger={
            <Button type={type} disabled>
              {intl.get({
                id: 'code-assets.src.utils.locale.CreateACodeLibrary',
                defaultMessage: '新建代码库',
              })}
            </Button>
          }
          align="t"
          text={intl.get({
            id: 'code-assets.tb-project-repos.containers.root.CurrentlyTheEnterpriseHasEnabled',
            defaultMessage: '当前企业开启了创建库的权限管控，如有需要请联系企业管理员修改',
          })}
        />
      );
    }
    return (
      <Dropdown
        trigger={
          <Button
            type={type}
            id="tb-project-dropdown-btn"
            text
            onClick={() => {
              track({
                action: 'add repo',
                page: 'DevOps Codeup Page',
                type: '',
                control: '',
              });
            }}
          >
            <YunxiaoIcon type="add-fill" />
            {intl.get({
              id: 'code-assets.tb-project-repos.containers.root.AddCodeLibrary',
              defaultMessage: '添加代码库',
            })}
          </Button>
        }
        safeNode={() => document.querySelector('#tb-project-dropdown-btn')}
        triggerType="click"
        align="tr br"
      >
        <Menu>
          <Menu.Item
            onClick={() => {
              track({
                action: 'link repo',
                page: 'DevOps Codeup Page',
                type: '',
                control: 'new repo',
              });

              webApp.toggleLift(true);
              this.setState({
                createModalShow: true,
              });
            }}
          >
            {intl.get({
              id: 'code-assets.tb-project-repos.containers.root.CreateACodeLibrary',
              defaultMessage: '新建代码库',
            })}
          </Menu.Item>
          <Menu.Item
            onClick={() => {
              track({
                action: 'link repo',
                page: 'DevOps Codeup Page',
                type: '',
                control: 'link repo',
              });

              webApp.toggleLift(true);
              this.setState({
                linkModalShow: true,
              });
            }}
          >
            {intl.get({
              id: 'code-assets.tb-project-repos.containers.root.AssociateExistingDatabases',
              defaultMessage: '关联已有库',
            })}
          </Menu.Item>
          {/* <Menu.Item
             onClick={() => {
               track({
                 action: 'link repo',
                 page: 'DevOps Codeup Page',
                 type: '',
                 control: 'import repo',
               });
               webApp.toggleLift(true);
               this.setState({
                 importModalShow: true,
               });
             }}
            >
             导入代码库
            </Menu.Item> */}
        </Menu>
      </Dropdown>
    );
  };

  closeModal = (type) => {
    webApp.toggleLift(false);
    this.setState({
      [type]: false,
    });
  };

  pageChange = (value) => {
    this.props.getProjects(value);
  };

  filterLevel = (level) => {
    let label = '';
    visibility_levels.forEach((item) => {
      if (item.value === Number(level)) {
        label = item.label;
      }
    });
    return label;
  };

  getDataSource = () => {
    const { projects } = this.props;
    return projects
      ? projects.map((project) => {
          const buildRes = (
            <div style={{ width: 144 }}>
              {project.last_commit && (
                null
                // <TbBuildResultTag
                //   projectId={project.id}
                //   commitId={project.last_commit}
                //   webApp={webApp}
                // />
              )}
            </div>
          );

          const mrCnt = (
            <div style={{ width: 100 }}>
              <Balloon.Tooltip
                align="t"
                trigger={
                  <Button
                    type="normal"
                    text
                    onClick={(e) => {
                      e.stopPropagation();
                      e.preventDefault();
                      // 有default_branch则不为空库，可跳转
                      if (project.default_branch) {
                        navigateOpen(`${project.web_url}/merge_requests`);
                      }
                    }}
                  >
                    <YunxiaoIcon type="pull-request-line" /> {project.opened_mr_count}
                  </Button>
                }
              >
                {intl.get({
                  id: 'code-assets.tb-project-repos.containers.root.EnabledMergeRequest',
                  defaultMessage: '[开启的] 合并请求',
                })}

                {project.opened_mr_count}
              </Balloon.Tooltip>
            </div>
          );

          return {
            left: (
              <TextAvatar text={project.path.toUpperCase()} image={project.avatar_url} isCover />
            ),

            body: {
              title: (
                <PathEllipsis path={utils.getGroupPath(project.name_with_namespace)} size="large" />
              ),

              description: [
                <span className="project-list-item-desc">
                  {project.description ? (
                    <React.Fragment>
                      <span className="project-list-item-desc-project-desc">
                        <Title trigger={<span>{project.description}</span>}>
                          <div>{project.description}</div>
                        </Title>
                      </span>
                      <span className="project-list-item-desc-divider">·</span>
                    </React.Fragment>
                  ) : null}
                  <span className="project-list-item-desc-time">
                    {`${intl.get({
                      id: 'code-assets.src.utils.locale.UpdatedOn',
                      defaultMessage: '更新于',
                    })}${utils.getBeautyTime(project.last_activity_at)}`}
                  </span>
                </span>,
              ],
            },

            middle: {
              items: [buildRes, project.default_branch ? mrCnt : null],
            },

            right: {
              hoverItems: [
                <BalloonConfirm
                  type="warning"
                  align={'lt'}
                  title={intl.get({
                    id: 'code-assets.tb-project-repos.containers.root.Disassociate',
                    defaultMessage: '取消关联',
                  })}
                  content={intl.get(
                    {
                      id: 'code-assets.tb-project-repos.containers.root.AreYouSureYouWant',
                      defaultMessage: '确认取消关联代码库 {projectName}？',
                    },
                    { projectName: project.name },
                  )}
                  triggerType="click"
                  followTrigger
                  trigger={
                    <span
                      onClick={(e) => {
                        e.preventDefault();
                      }}
                    >
                      <Button type="secondary" color="gray" text>
                        {intl.get({
                          id: 'code-assets.tb-project-repos.containers.root.Disassociate',
                          defaultMessage: '取消关联',
                        })}
                      </Button>
                    </span>
                  }
                  okFn={(cb) => {
                    this.props.unlinkProject(project.id);
                    cb &&
                      cb({
                        visible: false,
                      });
                  }}
                />,
              ],

              items: [
                <span>
                  <Tag size="small">{this.filterLevel(project.visibility_level)}</Tag>
                </span>,
              ],

              style: {
                width: 84,
                justifyContent: 'center',
              },
            },

            container: 'a',
            containerProps: {
              href: `/${project.path_with_namespace}`,
              target: '_blank',
            },
          };
        })
      : [];
  };

  renderContent = (dataSource) => {
    // const { currentPage, total } = this.props;
    // const hasMore = currentPage * defaultPageSize < total;

    return (
      <React.Fragment>
        <List
          dataSource={dataSource}
          // pagination={{
          //   onLoadMore: (page) => {
          //     this.props.getProjects(page);
          //   },
          //   hasMore,
          //   useWindow: false,
          //   getScrollParent: () => {
          //     return document.querySelector('#container');
          //   },
          // }}
          hasHoverItems
        />
      </React.Fragment>
    );
  };

  renderEmpty = () => {
    const hasCreateGroupAccess = this.getCreateProjectAccess();

    return (
      <div className="tb-repo-list-empty-wrapper">
        <div className="tb-repo-list-empty">
          <div className="tb-repo-list-empty-title">
            {intl.get({
              id: 'code-assets.tb-project-repos.containers.root.WelcomeToTheCloudEffect',
              defaultMessage: '欢迎来到云效代码管理 Codeup',
            })}
          </div>
          <div className="tb-repo-list-empty-desc">
            {intl.get({
              id: 'code-assets.tb-project-repos.containers.root.AddACodeLibraryTo',
              defaultMessage: '添加代码库开始编码开发',
            })}
          </div>
          {hasCreateGroupAccess ? (
            <div className="tb-repo-list-empty-btns">
              <Button
                type="primary"
                onClick={() => {
                  track({
                    action: 'link repo',
                    page: 'DevOps Codeup Page',
                    type: 'empty list',
                    control: 'new repo',
                  });

                  webApp.toggleLift(true);
                  this.setState({
                    createModalShow: true,
                  });
                }}
                style={{ marginRight: 8 }}
              >
                {intl.get({
                  id: 'code-assets.tb-project-repos.containers.root.CreateACodeLibrary',
                  defaultMessage: '新建代码库',
                })}
              </Button>
              <Button
                type="normal"
                onClick={() => {
                  track({
                    action: 'link repo',
                    page: 'DevOps Codeup Page',
                    type: 'empty list',
                    control: 'link repo',
                  });

                  webApp.toggleLift(true);
                  this.setState({
                    linkModalShow: true,
                  });
                }}
              >
                {intl.get({
                  id: 'code-assets.tb-project-repos.containers.root.AssociateExistingDatabases',
                  defaultMessage: '关联已有库',
                })}
              </Button>
            </div>
          ) : null}
          <div className="tb-repo-list-empty-img">
            <img src="https://img.alicdn.com/tfs/TB1Vogwtxn1gK0jSZKPXXXvUXXa-1920-810.png" />
          </div>
        </div>
      </div>
    );
  };

  render() {
    const { projectListLoaded, total, tbProjectName } = this.props;
    const { createModalShow, linkModalShow } = this.state;
    // 根据tab 获取数据
    const dataSource = this.getDataSource();

    return (
      <Layout>
        <Header
          title={
            <>
              {intl.get({
                id: 'code-assets.tb-project-repos.containers.root.CodeBase',
                defaultMessage: '代码库',
              })}
              {projectListLoaded ? ` · ${total}` : null}
            </>
          }
          operation={this.renderAddBtn()}
        />
        <Body>
          <BodyContent>
            <Content>
              {projectListLoaded ? (
                <React.Fragment>
                  <Perf page="DevOps Codeup Page" />
                  {dataSource.length === 0 ? (
                    this.renderEmpty()
                  ) : (
                    <div>{this.renderContent(dataSource)}</div>
                  )}
                </React.Fragment>
              ) : (
                <div style={{ marginTop: 100 }}>
                  <ListLoading />
                </div>
              )}
            </Content>
          </BodyContent>
        </Body>

        {/* 新建 */}
        {createModalShow ? (
          <CreateProjectModal
            defaultNamespaceId={defaultNamespaceId}
            closeModal={() => {
              this.closeModal('createModalShow');
            }}
            tbProjectName={tbProjectName}
            tbProjectId={tbProjectId}
            isModalOpen={createModalShow}
            okFn={() => {
              track({
                action: 'complete link repo',
                page: 'DevOps Codeup Page',
                type: '',
                control: 'complete new repo',
              });

              this.reloadData();
            }}
          />
        ) : null}
        {/* 关联 */}
        {linkModalShow && (
          <LinkProjectModal
            tbProjectId={tbProjectId}
            closeModal={() => {
              this.closeModal('linkModalShow');
            }}
            okFn={() => {
              track({
                action: 'complete link repo',
                page: 'DevOps Codeup Page',
                type: '',
                control: 'complete link repo',
              });

              this.reloadData();
            }}
            isModalOpen={linkModalShow}
          />
        )}
      </Layout>
    );
  }
}

export default connect(
  (state) => state,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
